<template>
  <div class="ssal-calendar-container" ref="fiveweek">
    <div class="week-area">
      <div
        :class="['week-cell']"
        v-for="(item, index) in weekTitle"
        :key="index"
      >
        周{{ item.day }}
      </div>
    </div>
    <div class="month-area">
      <div class="month-area-container">
        <div
          class="month-row"
          :style="{
            zIndex: drapIS ? (langData[index] ? '3' : '1') : langData[index] ? '2' : '1',
          }"
          v-for="(item, index) in weeks"
          :key="index"
        >
          <div class="month-view">
            <div
              v-for="(date, idx) in item"
              ref="monthCube"
              :class="[
                'month-date',
                date.disable ? 'date-disabled' : '',
                date.weekend ? 'date-weekend' : '',
              ]"
              :key="idx"
              :data-date="date.fullDate"
              :data-index="index"
              :data-idx="idx"
              @contextmenu.prevent="handleMonthRight"
              @click.prevent="handleMonthLeft($event, date)"
              @dragleave="handledragLevel($event)"
              @drop="handledragLevel($event)"
            >
              <div
                :class="['original-day', date.isDay ? 'current-day' : '']"
                :data-index="index"
                :data-idx="idx"
                :data-date="date.fullDate"
              >
                <div
                  :class="['day', date.isDay ? 'today' : '']"
                  :style="{
                    width: Number(weeks[index][idx].date) === 1||date.isDay ? 'auto' : '20px',
                  }"
                  :data-date="date.fullDate"
                  :data-index="index"
                  :data-idx="idx"
                >
                  <text v-if="Number(weeks[index][idx].date) === 1">{{
                     Number(weeks[index][idx].month) + "-"
                  }}</text>
                  <!-- <text style="width:20px;heigth:20px;border-radius:50%;background:#18A058;color:#fff;text-align:center;line-height: 20px;" v-if="date.isDay">今</text> -->
                  <text
                    :class="[
                      'day1',
                      Number(weeks[index][idx].date) === 1 ? 'today1' : '',
                    ]"
                  >
                    {{ Number(date.date) }}</text
                  >
                </div>
                <template v-if="date.lunar">
                  <div
                    class="lunar"
                    v-if="date.lunar.LoveThisDay!=undefined"
                    :data-index="index"
                    :data-idx="idx"
                    :data-date="date.fullDate"
                  >
                   {{ date.lunar.LoveThisDay }}
                  </div>
                  <div
                    class="lunar"
                    v-else-if="date.lunar.lunarFestival!=undefined"
                    :data-index="index"
                    :data-idx="idx"
                    :data-date="date.fullDate"
                  >

                   {{ date.lunar.lunarFestival }}
                  </div>
                  <div
                    class="lunar"
                    v-else-if="date.lunar.Term==='清明'"
                    :data-index="index"
                    :data-idx="idx"
                    :data-date="date.fullDate"
                  >

                   {{ date.lunar.Term }}
                  </div>
                </template>
              </div>
              <div class="day-container">
                <div
                  v-for="day in 2"
                  :key="day"
                  class="day-cube"
                  ref="dayCube"
                  :data-index="index"
                  :data-idx="idx"
                  :data-position="day - 1"
                ></div>
              </div>
            </div>
          </div>
          <event-month-item
            :show_newData="showNewData"
            :eventArr="eventDataArr"
            :v="vv"
            :s="ss"
            v-if="events.length && weeks"
            :qq="qqq"
            @q="qp"
            @k="kk"
            @d="dd"
            @langEvent="langStartData"
            @langStartEventZIndex="langStartDataZIndex"
            @loadingRefers="loadingRefer"
            :vipToast="vipToast1"
            :events="events"
            :month="weeks"
            :row-index="index"
            :cube="monthCube"
            :dropData="dropMessage"
            :drapCount="drapCount1"
            @vipFunction="vipFunctionLive"
            @getMonthEvent="getMonthEvent"
            @exchangeDate="exchangeDate"
            @closeModal="closeMore"
            @editInfo="getEventInfo"
            @delEvent="delEvent"
            @completeEvent="completeEvent"
            @moreEventHandle="moreEventHandle"
            @emupdateActive="activeBorderEvent"
            @approverAccess="approverAccess"
            @approverReject="approverReject"
            @readInfo="readInfo"
          >
          <!-- :drapIndex="drapIndex1" -->

            <template v-slot:default="slotItem">
              <span :style="{textDecoration: slotItem.state == 2 ? 'line-through' : 'unset'}" class="slot-data">
                <template v-if="slotItem.codeName">{{ slotItem.codeName }}·</template> 
                <pennant 
                  v-if="Number(slotItem.targetType) === 1 || Number(slotItem.targetType) === 0"
                  style="margin-left:3px"
                  theme="filled" 
                  size="13" 
                  :fill="slotItem.color"
                />
                <template v-if="slotItem.state == -1">
                  <file-date-one style="top: 2px;position: relative;" theme="outline" size="12" :fill="slotItem.color" />
                  (待审核)
                </template>
                <template v-else-if="slotItem.state == -2">
                  <close-one style="top: 1px;position: relative;" theme="outline" size="12" :fill="slotItem.color" />
                  (已驳回)
                </template>
                <template v-else-if="slotItem.state == 3">
                  <file-withdrawal style="top: 2px;position: relative;" theme="outline" size="12" :fill="slotItem.color" />
                  (已退回)
                </template>
                {{ slotItem.title || "（无主题）" }}
              </span>
            </template>
            <template v-slot:num="slotItem">
              {{ slotItem.num ? `(${slotItem.num})` : "" }}
            </template>
          </event-month-item>
        </div>
      </div>
      <div v-if="showTime" class="time-placeholder-box time-month-placeholder-box">
        <div class="close-bg" @click="showTime = false"></div>
        <div
          class="time-placeholder timeRef"
          :style="{
            top: timeDistance.top,
            left: timeDistance.left,
            width: 'calc(100% / 7)',
            marginLeft: 0,
          }"
          id="timeRef"
        >
          添加事件
        </div>
      </div>
    </div>
    <model-option-box
      v-model:dialogModelVisible="dialogModelVisible"
      :type="modelType"
      :valueData="evDataList"
      @close-form="CloseModel"
      @get-quick="getQuick"
    ></model-option-box>
    <!-- <EventDetail
      :dialogEventDetailVisible="dialogEventDetailVisible"
      :event="itemInfo"
      @edit-info="editInfo"
      @del-event="delEvent"
    ></EventDetail> -->
    <EventForm
      :dialogEventFormVisible="dialogEventFormVisible"
      :code="formCode"
      :item-id="itemId"
      :title="formTitle"
      :eventId="eventId"
      :readOnly="readOnly"
      @CloseForm="CloseForm"
    ></EventForm>


  </div>
</template>

<script>
import { ref, toRefs, provide, reactive, getCurrentInstance } from "vue";
import { ElMessage } from 'element-plus'
import { Pennant, FileDateOne, CloseOne, FileWithdrawal } from '@icon-park/vue-next'
import EventMonthItem from "../EventMonthItem/index.vue";
import ModelOptionBox from "../ModelOptionBox/index.vue";
// import EventDetail from "../EventDetail/AuthorityManage.vue";
import EventForm from "../EventForm/index.vue";

import { formatTime } from "../lib/event.js";
import { currentForm } from "../lib/config.js";

import { homeApi } from "/@/api/home/index";

export default {
  name: "FiveWeek",
  components: {
    EventMonthItem,
    ModelOptionBox,
    // EventDetail,
    EventForm,
    Pennant,
    FileDateOne,
    CloseOne,
    FileWithdrawal
  },
  props: {
    weekTitle: {
      type: Array,
      default() {
        return [];
      },
    },
    weeks: {
      type: Array,
      default() {
        return [];
      },
    },
    events: {
      type: Array,
      default() {
        return [];
      },
    },
    scrollDisabled: {
      type: Boolean,
      default: false,
    },
    belongsUser: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  emits: ["exchangeDate", "closeMore", "update:scrollDisabled"],
  setup(props, context) {
    const { events, weeks } = toRefs(props);
    const { proxy } = getCurrentInstance()
    const homeCalendar = homeApi();
    const state = reactive({
      formCode: null,
      itemId: null,
      formTitle: null,
      // 当前存在的事项
      formExist: currentForm,
      eventId: null, // 编辑的id
      readOnly: false, // 只读
    })

    const statusUserUs = ref(true);
    let vv = ref([false, false, false, false, false]);
    let ss = ref([true, true, true, true, true]);
    let langData = ref([false, false, false, false, false]);
    let langDataZIndex = ref([false, false, false, false, false]);
    let drapIS = ref(false);
    let chushaiStatus = ref(false);
    let langStartData = (content) => {
      if (content.over === "0") {
        langData.value[content.index] = true;
      } else {
        langData.value[content.index] = false;
      }
    };
    let langStartDataZIndex = (content) => {
      drapIS.value = content;
    };
    provide("statusUserUs", statusUserUs);
    let showTime = ref(false);
    let showHeaderTime = ref(false);
    let timeDistance = ref({
      top: 0,
      left: 0,
    });
    let statusVip = ref([false, false, false, false, false]);
    let qqq = ref(false);
    // 这里进行重新排序代码
    let eventDataArr = ref([]);
    let qp = (em) => {
      qqq.value = em.over;
    };
    const monthCube = ref();
    const dayCube = ref();
    let dropMessage = ref({});
    let defaultForm = ref({});
    let itemInfo = ref({});
    let num = 0;
    let dialogModelVisible = ref(false);
    let dialogEventDetailVisible = ref(false);
    let dialogEventFormVisible = ref(false);
    let modelType = ref(1);
    const handledragLevel = (e) => {
      dropMessage.value = e.target.dataset;
      e.target.style.background = "unset";
    };
    // monthEvent
    const getMonthEvent = (e) => {
      if (e) {
        const id = e.target ? e.target.dataset.id : e.dataset.id;
        const info = events.value.find((item) => {
          return item.id == id;
        });
        itemInfo.value = {
          info,
          ele: e,
        };
        // dialogEventDetailVisible.value = !dialogEventDetailVisible.value;
      }
    };
    let drapCount1 = ref("-1");
    // let drapIndex1 = ref([]);
    const activeBorderEvent = (e) => {
      if (e.over === true) {
        drapCount1.value = e.id;
        // drapIndex1.value = e.indexArr;
      } else {
        drapCount1.value = "-1";
        // drapIndex1.value = [];
      }
    };
    const exchangeDate = (e) => {
      context.emit("exchangeDate", e);
    };
    const closeMore = () => {
      context.emit("closeMore", true);
      context.emit("update:scrollDisabled", false);
    };
    let evDataList = ref([]);
    let thisTime = ref("");
    // 左键月
    const handleMonthLeft = (e, date) => {
      thisTime.value = date.fullDate;
      num++;
      setTimeout(() => {
        context.emit("update:scrollDisabled", true);
        let easyList = evDataList.value;
        evDataList.value = [];
        evDataList.value = easyList
        if (num == 1) {
          modelType.value = 1;
          getMonthDistance(e);
        }

        // 这里可能要调接口

        if (num == 2) {
          // const { fullDate } = getMonthDistance(e);
          // defaultForm.value["startTime"] = fullDate + " 00:00";
          // defaultForm.value["endTime"] = fullDate + " 23:59";
          // defaultForm.value["isAllDay"] = true;
          // dialogEventFormVisible.value = !dialogEventFormVisible.value;
          // modelType.value = 2
          // getMonthDistance(e);
          // dialogModelVisible.value = !dialogModelVisible.value;
          // context.emit('update:scrollDisabled', true)
          // console.log("双击");
        }
        if (num > 2) {
          num = 0;
        }
        num = 0;
        dialogModelVisible.value = !dialogModelVisible.value;

       // 将当前点击的时间的值保存到全局
       const position = e.target.dataset.position || 0
       let time = date.fullDate
       if(position == 1) {
        // 下午
        time += ' 14:00:00'
       } else {
        time += ' 09:00:00'
       }
       proxy.mittBus.emit('setCurrentClickTime', time)
      }, 250);
    };
    // 右键月
    const handleMonthRight = (e) => {
      // getMonthDistance(e);
    };
    // 关闭model
    const CloseModel = () => {
      showHeaderTime.value = false;
      showTime.value = false;
      context.emit("update:scrollDisabled", false);
    };
    // 获取月的事件格子距离
    const getMonthDistance = (e) => {
      const index = e.target.dataset.index;
      const idx = e.target.dataset.idx;
      const position = e.target.dataset.position || 0;
      const arr = Object.keys(weeks.value);
      timeDistance.value.top = `calc((100% / ${arr.length}) * ${index} + 28px + ${
        position * dayCube.value[0].offsetHeight
      }px)`;
      timeDistance.value.left = `calc(100% / ${weeks.value[index].length} * ${idx})`;
      showTime.value = true;
      return {
        fullDate: e.target.dataset.date,
      };
    };
    let showNewData = ref(true);

    // 获取
    const getQuick = (e) => {
      // 判断是否存在code
      const isExist = state.formExist.find(item => item == e.code)
      if(!isExist) {
        ElMessage.error(`${e.name}\n创建操作不存在`)
        return
      }
      // 把所选tag的类型传到表单组件里面去， 根据所选tag类型展示对应的表单内容
      state.formCode = e.code
      state.itemId = e.id
      state.formTitle = e.name
      state.eventId = null
      setTimeout(() => {
        context.emit("update:scrollDisabled", true);
      }, 300);
      dialogEventFormVisible.value = !dialogEventFormVisible.value;
    };
    const overScroll = () => {
      context.emit("update:scrollDisabled", false);
    };
    // const editInfo = (e) => {
    //   defaultForm.value = e;
    //   dialogEventFormVisible.value = !dialogEventFormVisible.value;
    // };
    // 删除form
    const delEvent = (e) => {
      context.emit("delEvent", e);
      // dialogEventDetailVisible.value = !dialogEventDetailVisible.value;
    };
    // 关闭Form
    const CloseForm = () => {
      // showHeaderTime.value = false;
      // showTime.value = false;
      // defaultForm.value = {};
      context.emit("update:scrollDisabled", false);
    };
    // 获取form
    const getForm = (e) => {
      context.emit("submitForm", e);
    };
    // 完成事件
    const completeEvent = (e) => {
      context.emit("completeEvent", e);
    };
    // 更多事件操作
    const moreEventHandle = () => {
      context.emit("update:scrollDisabled", true);
    };
    let vipToast1 = ref(true);
    const vipFunctionLive = (e) => {
      // console.log(e);
      vipToast1.value = e;
    };
    let kk = (e) => {
      // console.log(e);
      for (let i = 0; i < vv.value.length; i++) {
        vv.value[i] = false;
      }
      vv.value[e.rowIndex] = e.b;
    };
    const loadingRefer = (e) => {
      if(e){
        showNewData.value = false
      }else{
        showNewData.value = true
      }

    }
    let dd = (e) => {
      if (e.all) {
        ss.value = [true, true, true, true, true];
      } else {
        // console.log(e);
        for (let i = 0; i < ss.value.length; i++) {
          ss.value[i] = false;
        }
        ss.value[e.rowIndex] = e.b;
      }
    };
    // 获取事项编辑的数据
    const getEventInfo = (e) => {
      state.eventId = e.id
      state.formCode = e.code
      state.formTitle = e.codeName
      const isExist = state.formExist.find(item => item == e.code)
      if(!isExist) {
        ElMessage.error(`${e.codeName}\n编辑操作不存在`)
        return
      }
      context.emit("update:scrollDisabled", true);
      dialogEventFormVisible.value = !dialogEventFormVisible.value
    }
    // 查看事项
    const readInfo = (e) => {
      state.eventId = e.id
      state.formCode = e.code
      state.formTitle = e.codeName
      state.readOnly = true
      const isExist = state.formExist.find(item => item == e.code)
      if(!isExist) {
        ElMessage.error(`${e.codeName}\n查看操作不存在`)
        return
      }
      context.emit("update:scrollDisabled", true);
      dialogEventFormVisible.value = !dialogEventFormVisible.value
    }
    // 审批通过
    const approverAccess = e => {
      context.emit('approverAccess', e)
    }
    // 审批拒绝
    const approverReject = e => {
      context.emit('approverReject', e)
    }
    return {
      ...toRefs(state),
      monthCube,
      dropMessage,
      handledragLevel,
      getMonthEvent,
      defaultForm,
      showTime,
      exchangeDate,
      closeMore,
      handleMonthLeft,
      handleMonthRight,
      CloseModel,
      timeDistance,
      dialogModelVisible,
      getQuick,
      dialogEventDetailVisible,
      // editInfo,
      delEvent,
      itemInfo,
      dayCube,
      dialogEventFormVisible,
      CloseForm,
      getForm,
      completeEvent,
      moreEventHandle,
      modelType,
      vipFunctionLive,
      vipToast1,
      statusUserUs,
      statusVip,
      vv,
      kk,
      ss,
      dd,
      langData,
      langStartData,
      langDataZIndex,
      langStartDataZIndex,
      drapIS,
      qqq,
      qp,
      evDataList,
      activeBorderEvent,
      drapCount1,
      thisTime,
      eventDataArr,
      showNewData,
      loadingRefer,
      getEventInfo,
      approverAccess,
      approverReject,
      readInfo
    };
  },
};
</script>

<style lang="scss" scoped>
.ssal-calendar-container {
  height: calc(100% - 41px);
  border: 1px solid #e4e7ed;
  position: relative;
  box-sizing: border-box;
  .week-area {
    display: flex;
    align-items: stretch;
    justify-content: space-between;
    height: 30px;
    box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.06);
    .week-cell {
      width: calc(100% / 7);
      text-align: center;
      border-right: 1px solid #e4e7ed;
      font-size: 13px;
      color: #303133;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      &:last-child {
        border-right: none;
      }
    }
    .week-red {
      color: #f56c6c;
    }
  }
  .month-area {
    height: calc(100% - 30px);
    cursor: pointer;
    min-height: 470px;
    .month-area-container {
      height: 100%;
      min-height: 470px;
      cursor: pointer;
      overflow: auto;
      overflow-y: scroll;
      display: flex;
      justify-content: space-between;
      flex-direction: column;
      margin-right: -7px;
    }
    .month-row {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      position: relative;
      &:last-child {
        .month-view {
          .month-date {
            border-bottom: none;
          }
        }
      }
    }
    .month-view {
      display: flex;
      flex-wrap: wrap;
      align-items: stretch;
      flex: 1;
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      height: 100%;
      .month-date {
        width: calc(100% / 7);
        height: 100%;
        border-right: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        &:last-child {
          border-right: none;
        }
      }
      .original-day {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 4px 5px 4px 2px;
      }
      .lunar {
        font-size: 12px;
        color: #909399;
        max-width: 50%;
        white-space: nowrap;
        overflow: hidden;//文本超出隐藏
        text-overflow: ellipsis;//文本超出省略
      }
      .day {
        color: #303133;
        font-size: 14px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
      }
      .date-disabled .day,
      .date-disabled .lunar {
        color: #c0c4cc;
        opacity: 0.6;
      }
      .date-weekend .day {
        color: #f56c6c !important;
      }
      .today {
        // color: #fff !important;
        // background: var(--ss-color-primary);
        border-radius: 50%;
      }
      .day1 {
        color: #303133;
        font-size: 14px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: normal;
      }

      .current-day{
        background: var(--el-color-primary-light-9);
        .day1{
          font-weight: bold;
          color: var(--el-color-primary);
        }
      }
      .today1 {
        // color: #fff !important;
        // background: var(--ss-color-primary);
        // border-radius: 50%;
        color: #f56c6c !important;
        padding: 0 !important;
        margin: 0 !important;
        width: auto;
      }
      .date-weekend .today {
        // color: #fff !important;
      }
      .day-container {
        flex: 1;
        overflow: hidden;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
        .day-cube {
          flex: 1;
          overflow: hidden;
        }
      }
    }
  }
  .time-placeholder {
    position: absolute;
    z-index: 999;
    margin-left: 80px;
    background: #ecf5ff;
    border: 1px dashed var(--ss-color-primary);
    font-size: 12px;
    text-align: center;
    color: var(--ss-color-primary);
    height: 20px;
    box-sizing: border-box;
    line-height: 20px;
  }
  .close-bg {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 998;
    background: rgba(0, 0, 0, 0.2);
  }
  .time-month-placeholder-box {
    position: absolute;
    top: 30px;
    left: 0;
    right: 0;
    bottom: 0;
  }
}
.tc_loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  .closebg {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1001;
    background: rgba(0, 0, 0, 0.12);
  }
}

.slot-data{
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 100%;
}
</style>
